package com.bridgeintelligent.tag.webserver.dim.mgmt.service.index;

import com.bridgeintelligent.tag.webserver.dim.mgmt.api.BaseCode;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DimException;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DimRep;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.model.DimCountModel;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static javax.servlet.http.HttpServletResponse.SC_OK;


/**
 * @description
 * @author: grp 2021-01-06 10:27
 **/
@Api(tags = "首页相关接口")
@RestController
@RequestMapping("/api/indexOther")
@AllArgsConstructor
@Validated
@Slf4j
public class IndexOtherController {

    private IndexOtherService indexOtherService;

    @ApiOperation(value = "首页-评价-数据-产品版")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "group", value = "分组", required = true),
            @ApiImplicitParam(paramType = "query", name = "catalogId", value = "目录id", required = true)})
    @GetMapping("/assessData")
    public DimRep<Object> assessData(@NotBlank String group, @NotBlank String catalogId) {
        try {
            List<AssessDataVO> data = indexOtherService.assessData(group, catalogId);
            return new DimRep<>(data, BaseCode.SUCCESS);
        } catch (DimException e) {
            return new DimRep<>(null,e.getCode(), "操作失败");
        }
    }

    @ApiOperation(value = "首页-评价-占比饼图-产品版")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "catalogId", value = "目录id", required = true)})
    @GetMapping("/assessPie")
    public DimRep<List<AssessPieVO>> assessPie(@NotBlank String catalogId) {
        try {
            List<AssessPieVO> data = indexOtherService.assessPie(catalogId);
            return new DimRep<>(data, BaseCode.SUCCESS);
        } catch (DimException e) {
            return new DimRep<>(null, e.getCode(), "操作失败");
        }
    }

    @ApiOperation(value = "首页-标签数量趋势-产品版")
    @PostMapping("/dimCount")
    public DimRep<CountVO> dimCount(@RequestBody @Valid DimCountModel model) {
        try {
            CountVO data = indexOtherService.dimCount(model);
            return new DimRep<>(data, BaseCode.SUCCESS);
        } catch (DimException e) {
            return new DimRep<>(null, e.getCode(), "操作失败");
        }
    }

    @ApiOperation(value = "首页-标签活跃数量-产品版")
    @GetMapping("/dimActive")
    public DimRep<List<DimActiveVO>> dimActive(){
        try {
            List<DimActiveVO> data = indexOtherService.dimActive();
            return new DimRep<>(data, BaseCode.SUCCESS);
        } catch (DimException e) {
            return new DimRep<>(null, e.getCode(), "操作失败");
        }
    }

    @ApiOperation(value = "标签数量趋势数据下载", notes = "下载")
    @PostMapping("/download/dimCount")
    public void export(@RequestBody @Valid DimCountModel model, HttpServletResponse response){
        CountVO data = indexOtherService.dimCount(model);
        List<Map<String, DimCountVO>> table = data.getTable();
        // 创建工作薄对象
        XSSFWorkbook workbook=new XSSFWorkbook();
        if(!CollectionUtils.isEmpty(table)){
            createSheet(model.getDates(),table, workbook);
        }else{
            XSSFSheet sheet=workbook.createSheet("标签数量趋势");
            XSSFRow title = sheet.createRow(0);
            title.createCell(0).setCellValue("标签目录");
        }
        // 创建文档信息
        try(OutputStream os=response.getOutputStream()) {
            response.reset();
            response.setStatus(SC_OK);
            String fileName = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s.xlsx\"", fileName));
            response.setContentType("application/msexcel");
            workbook.write(os);
            os.flush();
        } catch (IOException e) {
            log.error("标签数量趋势数据下载异常", e);
            throw new RuntimeException("标签数量趋势数据下载异常");
        }
    }

    private void createSheet(List<String> dates, List<Map<String, DimCountVO>> table, XSSFWorkbook workbook) {
        XSSFSheet sheet=workbook.createSheet("标签数量趋势");
        XSSFRow title = sheet.createRow(0);
        title.createCell(0).setCellValue("标签目录");
        for(int i = 1;i<=dates.size();i++){
            title.createCell(i).setCellValue(dates.get(i-1));
        }
        int k = 1;
        for(Map<String, DimCountVO> row : table){
            XSSFRow newRow = sheet.createRow(k++);
            newRow.createCell(0).setCellValue(row.get(dates.get(0)).getName());
            for(int j = 0;j<dates.size();j++){
                newRow.createCell(j+1).setCellValue(row.get(dates.get(j)).getCount());
            }
        }
    }
}
